package com.yinxing.framework.shiro.interceptor;

import com.yinxing.framework.shiro.exception.RequiresRolesException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.aop.RoleAnnotationHandler;

import java.lang.annotation.Annotation;
import java.util.Arrays;

public class MyRoleAnnotationHandler extends RoleAnnotationHandler {

    public void assertAuthorized(Annotation a) throws AuthorizationException {
        if (!(a instanceof RequiresRoles)) return;

        RequiresRoles rrAnnotation = (RequiresRoles) a;
        String[] roles = rrAnnotation.value();

        boolean hasRole = false;

        if (roles.length == 1) {
            hasRole = getSubject().hasRole(roles[0]);
        }
        if (Logical.AND.equals(rrAnnotation.logical())) {
            hasRole = getSubject().hasAllRoles(Arrays.asList(roles));
        }
        if (Logical.OR.equals(rrAnnotation.logical())) {
            for (String role : roles) if (getSubject().hasRole(role)) hasRole = true;
        }

        if(!hasRole) {
            String msg = "用户不具备所需角色" + Arrays.toString(roles) + "逻辑:" + rrAnnotation.logical();
            throw new RequiresRolesException(msg);
        }
    }
}
